<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>处理边界情况</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAHbknPTCvUSgWwU0jJ68m4h6b7vpyP6hM"></script>
    <style>
        .map {
            width: 100%;
            height: 400px;
        }
    </style>
</head>

<body>
    <!-- 访问父级组件实例 -->
    <div id="app">
        <google-map>
            <google-map-marker v-bind:places="vueConfCities"></google-map-marker>
        </google-map>
    </div>

    <!-- 访问子组件实例或子元素 -->
    <!-- this.$refs.usernameInput -->
    <div>
        <base-input ref="usernameInput"></base-input>
    </div>
</body>
<script>
    Vue.component("google-map", {
        // provide 允许我们指定我们想要提供给后代组件的数据/方法
        provide: function() {
          return {
            getMap: this.getMap
          };
        },
        data: function () {
            return {
                map: null
            };
        },
        mounted: function () {
            this.map = new google.maps.Map(this.$el, {
                center: { lat: 0, lng: 0 },
                zoom: 1
            });
        },
        methods: {
            getMap: function (found) {
                var vm = this;
                function checkForMap() {
                    if (vm.map) {
                        found(vm.map);
                    } else {
                        setTimeout(checkForMap, 50);
                    }
                }
                checkForMap();
            }
        },
        template: '<div class="map"><slot></slot></div>'
    });

    Vue.component("google-map-marker", {
        // inject 接收指定的我们想要添加在这个实例上的 property
        inject: ["getMap"],
        props: ["places"],
        created: function () {
            var vm = this;
            // this.$parent.getMap  访问父级组件中的getMap方法
            // vm.$parent.getMap(function (map) {
            vm.getMap(function (map) {
                vm.places.forEach(function (place) {
                    new google.maps.Marker({
                        position: place.position,
                        map: map
                    });
                });
            });
        },
        render(h) {
            return null;
        }
    });

    new Vue({
        el: "#app",
        data: {
            vueConfCities: [
                {
                    name: "Wrocław",
                    position: {
                        lat: 51.107885,
                        lng: 17.038538
                    }
                },
                {
                    name: "New Orleans",
                    position: {
                        lat: 29.951066,
                        lng: -90.071532
                    }
                }
            ]
        }
    });
</script>

</html>